"use client";
import {
  PageContainer,
  ProForm,
  ProFormDigit,
  ProFormText,
} from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, Card, Col, message, Row, Space } from "antd";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { RollbackOutlined } from "@ant-design/icons";
import { addRoleApi, updateRoleApi, getRoleApi } from "@/lib/api/system/role";
import { Role } from "@/lib/api/system/role.d";

export default function Page() {
  const { type } = useParams();
  const router = useRouter();
  const params = useSearchParams();
  const roleId = params.get("roleId");

  const title = type === "add" ? "新增角色" : "修改角色";

  const { run: addRole, loading: addRoleLoading } = useRequest(addRoleApi, {
    manual: true,
    onSuccess: () => {
      message.success("新增成功");
      router.back();
    },
    onError: (error: any) => {
      message.error(error.msg);
    },
  });

  const { run: updateRole, loading: updateRoleLoading } = useRequest(
    (params) => updateRoleApi({ ...params, roleId: roleId }),
    {
      manual: true,
      onSuccess: () => {
        message.success("修改成功");
        router.back();
      },
      onError: (error: any) => {
        message.error(error.msg);
      },
    },
  );

  const extraProps =
    type !== "add"
      ? {
          request: async () => {
            const res = await getRoleApi(roleId as string);
            return res.data;
          },
        }
      : {
          defaultFormValues: {
            parentId: 101,
          },
        };

  return (
    <PageContainer
      title={title}
      extra={
        <Button icon={<RollbackOutlined />} onClick={() => router.back()}>
          返回
        </Button>
      }
    >
      <Card>
        <ProForm
          layout="horizontal"
          submitter={{
            render: (_, dom) => {
              return (
                <Row>
                  <Col span={14} offset={4}>
                    <Space>{dom}</Space>
                  </Col>
                </Row>
              );
            },
            searchConfig: { submitText: "保存" },
          }}
          className="max-w-[800px] mx-auto my-10"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          loading={addRoleLoading || updateRoleLoading}
          onFinish={async (values: Role) => {
            if (type === "add") {
              await addRole({
                ...values,
                status: "0",
                deptCheckStrictly: true,
                menuCheckStrictly: true,
                dataScope: "1",
                deptIds: [],
                menuIds: [],
              });
            } else {
              await updateRole({
                ...values,
                status: "0",
                deptCheckStrictly: true,
                menuCheckStrictly: true,
                dataScope: "1",
                deptIds: [],
                menuIds: [],
              });
            }
          }}
          {...extraProps}
        >
          <ProFormText
            name="roleName"
            label="角色名称"
            rules={[{ required: true, message: "请输入角色名称" }]}
          />
          <ProFormText
            name="roleKey"
            label="权限字符"
            tooltip="控制器中定义的权限字符，如：@SaCheckRole('admin')"
            rules={[{ required: true, message: "请输入权限字符" }]}
          />
          <ProFormDigit
            min={0}
            fieldProps={{
              precision: 0,
            }}
            name="roleSort"
            label="角色顺序"
            rules={[{ required: true, message: "请输入角色顺序" }]}
          />
          <ProFormText name="menuIds" label="菜单权限" />
          <ProFormText name="remark" label="备注" />
        </ProForm>
      </Card>
    </PageContainer>
  );
}
